value={memo}

onChange={onChangeMemo}

/>

</Form.Group>

<Button variant="info" onClick={saveTodo}>

{editing ? "Edit" : "Add"} To-do

</Button>

</Form>

)}

</Container>

)

}

export default AddTodo;

* Contact [email protected] for the source code if you prefer to copy and paste

Code Explanation

Analyze Code

let editing = false;

let initialTodoTitle = "";

let initialTodoMemo = "";

const [title, setTitle] = useState(initialTodoTitle);

const [memo, setMemo] = useState(initialTodoMemo);

// keeps track if todo is submitted

const [submitted, setSubmitted] = useState(false);

The editing Boolean variable will be set to true if the component is in ‘Editing’ mode. False means we are adding a

todo.

We have a title state variable set to initialTodoTitle . In edit mode, initialTodoTitle will be set to the existing title text. The

same applies for memo and initialTodoMemo.

We also have a submitted state variable to keep track if the todo is submitted.

Analyze Code

const onChangeTitle = e => {

const title = e.target.value;

setTitle(title);

}

The onChangeTitle keeps track of the user-entered title value in the field:

Analyze Code

<Form.Control

type="text"

required

placeholder="e.g. buy gift tomorrow"

value={title}

onChange={onChangeTitle}

/>

The same applies to onChangeMemo. This should be familiar to you as we have used this before in the login form

fields.

Analyze Code

const saveTodo = () => {

var data = {

title: title,

memo: memo,

completed: false,

}

TodoDataService.createTodo(data, props.token)

.then(response => {

setSubmitted(true);

})

.catch(e => {

console.log(e);

});

}

saveTodo is called by the submit button’s onClick={saveTodo}. In saveTodo, we first create a data object containing the

todo’s properties, e.g. the todo title, memo, etc.